package com.example.learn_mybatis.controller;


import com.example.learn_mybatis.pojo.*;
import com.example.learn_mybatis.service.impl.UserRoleServiceImpl;
import com.example.learn_mybatis.service.impl.UsersServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chen
 * @since 2025-07-11
 */
@RestController
@RequestMapping("/users")
public class UsersController {
    @Autowired
    private UsersServiceImpl usersService;

    @Autowired
    private UserRoleServiceImpl userRoleService;

    /**
     * 获取所有的用户
     * @param pageParam
     * @return
     */
    @GetMapping
    public Result getUser(PageParam pageParam) {
        Pager allUser = usersService.getAllUser(pageParam.getSize(), pageParam.getPage());
        return Result.success(allUser);
    }

    /**
     * 新增用户
     * @param users
     * @return
     */
    @PostMapping
    public Result addUser(@RequestBody Users users) {
        usersService.save(users);
        return Result.success();
    }

    /**
     * 修改用户
     * @param users
     * @return
     */
    @PutMapping
    public Result updateUser(@RequestBody Users users) {
        boolean b = usersService.updateById(users);
        if(b){
            return Result.success();
        } else {
            return Result.error("更新失败");
        }
    }

    /**
     *  删除用户
     * @param id
     * @return
     */
    @DeleteMapping
    public Result deleteUser(Integer id) {
        boolean b = usersService.removeById(id);
        if(b){
            return Result.success();
        } else {
            return Result.error("删除失败");
        }
    }

    /**
     * 查询该用户所有的角色
     * @param pageParam
     * @return
     */
    @GetMapping("/roles")
    public Result getRolesByUserId(PageParam pageParam) {
        Pager rolesByUserPage = usersService.getRolesByUserId(pageParam.getId(), pageParam.getPage(), pageParam.getSize());
        return Result.success(rolesByUserPage);

    }

    /**
     * 批量新增该用户的角色
     * @param roleParam
     * @return
     */
    @PostMapping("/roles")
    public Result addRoles(@RequestBody RoleParam roleParam) {
        userRoleService.batchSaveUserRoles(roleParam);
        return Result.success();
    }

    /**
     * 根据ids批量删除
     * @param roleParam
     * @return
     */
    @DeleteMapping("/roles")
    public Result deleteRoles(@RequestBody RoleParam roleParam) {
        boolean b = userRoleService.batchRemoveById(roleParam);
        if(b){
            return Result.success();
        } else {
            return Result.error();
        }
    }

    /**
     * 获取用户所有的权限
     * @param pageParam
     * @return
     */
    @GetMapping("/permissions")
    public Result getPermissionsByUserId(PageParam pageParam) {
        List<Permissions> allPermission = usersService.getAllPermission(pageParam.getId());
        return Result.success(allPermission);
    }

}
